﻿using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;

namespace Swsk33.SimpleArcEngine.Dialog
{
	public partial class CityTreeView : Form
	{
		/// <summary>
		/// 传入地图控件
		/// </summary>
		private AxMapControl mapControl;

		/// <summary>
		/// 城市点集要素类
		/// </summary>
		private IFeatureClass layerFeatureClass;

		/// <summary>
		/// 传入缓冲区内点集
		/// </summary>
		private List<IFeature> features;

		/// <summary>
		/// 传入点击位置坐标，第一个元素是x，第二个是y
		/// </summary>
		private double[] bufferCenter;

		/// <summary>
		/// 城市树状信息带参构造器
		/// </summary>
		/// <param name="mapControl">传入地图控件</param>
		/// <param name="layerFeatureClass">传入城市要素类</param>
		/// <param name="features">传入缓冲区内点集</param>
		/// <param name="bufferCenter">传入点击位置坐标，第一个元素是x，第二个是y</param>
		public CityTreeView(AxMapControl mapControl, IFeatureClass layerFeatureClass, List<IFeature> features, double[] bufferCenter)
		{
			this.mapControl = mapControl;
			this.layerFeatureClass = layerFeatureClass;
			this.features = features;
			this.bufferCenter = bufferCenter;
			InitializeComponent();
		}

		/// <summary>
		/// 显示城市树状信息
		/// </summary>
		public void ShowCityTreeViewDialog()
		{
			int filedIndex = layerFeatureClass.FindField("CITY_NAME");
			foreach (IFeature feature in features)
			{
				TreeNode cityNode = new TreeNode();
				cityNode.Text = feature.Value[filedIndex].ToString();
				// 计算距离
				double distance = Math.Sqrt(Math.Pow(Math.Abs(bufferCenter[0] - ((IPoint)feature.Shape).X), 2) + Math.Pow(Math.Abs(bufferCenter[1] - ((IPoint)feature.Shape).Y), 2));
				TreeNode distanceNode = new TreeNode();
				distanceNode.Text = distance.ToString();
				cityNode.Nodes.Add(distanceNode);
				resultTreeView.Nodes.Add(cityNode);
			}
			ShowDialog();
		}

		private void resultTreeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			string cityName;
			if (e.Node.Parent == null)
			{
				cityName = e.Node.Text;
			}
			else
			{
				cityName = e.Node.Parent.Text;
			}
			IQueryFilter filter = new QueryFilter();
			filter.SubFields = "*";
			filter.WhereClause = "CITY_NAME = \'" + cityName + "\'";
			IFeatureCursor cursor = layerFeatureClass.Search(filter, false);
			IFeature feature = cursor.NextFeature();
			resultListView.Items.Clear();
			// 遍历字段值
			for (int i = 0; i < feature.Fields.FieldCount; i++)
			{
				IField field = feature.Fields.Field[i];
				ListViewItem item = resultListView.Items.Add(field.Name);
				if (field.Name.Equals("Shape"))
				{
					item.SubItems.Add("几何图形数据");
				}
				else
				{
					item.SubItems.Add(feature.Value[feature.Fields.FindField(field.Name)].ToString());
				}
			}
			new Thread(() =>
			{
				// 闪烁（异步）
				mapControl.FlashShape(feature.Shape);
			}).Start();
		}
	}
}